package com.itheima.bos.service.system.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itheima.bos.dao.system.MenuRepository;
import com.itheima.bos.dao.system.PermissionRepository;
import com.itheima.bos.dao.system.RoleRepository;
import com.itheima.bos.domain.system.Menu;
import com.itheima.bos.domain.system.Permission;
import com.itheima.bos.domain.system.Role;
import com.itheima.bos.domain.system.User;
import com.itheima.bos.service.system.IPermissionService;
import com.itheima.bos.service.system.IRoleService;

import freemarker.template.utility.StringUtil;
@Service
@Transactional
public class RoleServiceImpl implements IRoleService {
	
	@Autowired
	private RoleRepository roleRepository;
	
	@Autowired
	private PermissionRepository permissionRepository;
	
	@Autowired
	private MenuRepository menuRepository;
	
	@Override
	public List<Role> findByUser(User user) {
		
		if (user.getUsername().equals("admin")) {
			//就对该用户授权
			//admin具有所有的角色
			return roleRepository.findAll();
		}else {
			return roleRepository.findByUser(user.getId());
		}
	}

	@Override
	public List<Role> findAll() {
		
		return roleRepository.findAll();
	}

	@Override
	public void save(Role model, String[] permissionIds, String meniIds) {
		
		//关联权限,通过id查询出permission再关联role
		if (permissionIds!=null) {
			for (String permissionId : permissionIds) {
				Permission permission=permissionRepository.findOne(Integer.parseInt(permissionId));
				
				model.getPermissions().add(permission);
			}
		}
		//关联菜单
		if (StringUtils.isNotBlank(meniIds)) {
			String[] menuIds = meniIds.split(",");
			for (String menuId : menuIds) {
				Menu menu = menuRepository.findOne(Integer.parseInt(menuId));
				model.getMenus().add(menu);
			}
		}
		
		roleRepository.save(model);
		
	}
}
